# -*-coding:utf-8 -*-
# Author : Mo
# Data : 2022/2/4 20:53
from django.shortcuts import render,redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm


def user_list(request):
    """ 用户管理 """

    # 获取所有的用户列表 [obj,obj,obj]
    queryset = models.UserInfo.objects.all()
    """
        # 用python语法获取数据
    for obj in queryset:
        print(obj.id,obj.name,obj.age,obj.account,obj.create_time.strftime("%Y-%m-%d"),obj.get_gender_display(),obj.depart_id,obj.depart.title)
        # obj.depart_id # 获取数据库中存储的那个字段值
        # obj.depart.title # 根据id自动去关联的表中获取哪一行数据depart对象。
    """
    page_objrct = Pagination(request,queryset)
    context = {
        "queryset": page_objrct.page_queryset,
        "page_string" : page_objrct.html(),

    }
    return render(request,'user_list.html',context)


def user_add(request):
    """ 添加用户 """

    if request.method == "GET":
        context = {
            'gender_choices':models.UserInfo.gender_choices,
            "depart_list":models.Department.objects.all()
        }
        return render(request,"user_add.html",context)

    # 获取用户提交数据
    user = request.POST.get('user')
    password = request.POST.get('password')
    age = request.POST.get('age')
    account = request.POST.get('account')
    create_time = request.POST.get('create_time')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('depart_id')
    # 保存到数据库
    models.UserInfo.objects.create(name=user,password=password,age=age,
                                   account=account,create_time=create_time,
                                   gender=gender,depart_id=depart_id)
    # 重定向回部门列表
    return redirect("/user/list/")


# #################### ModelForm 示例 ####################
def user_model_form_add(request):
    """ 添加用户 """
    if request.method == "GET":
        form = UserModelForm()
        return render(request,"user_model_form_add.html", {"form": form})

    # 用户POST提交数据，数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '陈晨曦', 'password': '12345', 'age': 21, 'account': Decimal('1000'), 'create_time': datetime.datetime(2022, 1, 29, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'gender': 2, 'depart': <Department: 媒体企划>}
        # print(form.cleaned_data)
        form.save()
        return redirect("/user/list/")
    # 校验失败(在页面上显示错误信息)
    return render(request,'user_model_form_add.html',{"form":form})


def user_edit(request,nid):
    """ 编辑用户 """

    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据ID取数据库获取要编辑的哪一行数据(对象)
        form = UserModelForm(instance=row_object)
        return render(request,"user_edit.html",{"form":form})

    form = UserModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要在用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    return render(request,'user_edit.html',{"form":form})


def user_delete(request,nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')
